package team.first.movieapiv1pro.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import team.first.movieapiv1pro.domain.Token;
import team.first.movieapiv1pro.domain.TokenType;
import team.first.movieapiv1pro.domain.User;
import team.first.movieapiv1pro.service.UserService;
import team.first.movieapiv1pro.util.JWTHS256;
import team.first.movieapiv1pro.vo.ApiResponse;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Date;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv1pro.controller
 * @Date: 2021/12/24 15:32
 * @Description:
 */
@RestController
public class AuthorizationController {
    @Autowired
    UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/api/v1/authorization")
    public ApiResponse<Token> authorization(HttpServletRequest request) {
        ApiResponse apiResponse = new ApiResponse();
        int flag = (int) request.getAttribute("flag");

        switch (flag) {
            case 0 -> apiResponse.setCode(401).setSuccess(false).setMessage("未认证");
            case 1 -> apiResponse.setCode(403).setSuccess(false).setMessage("认证失败");
        }

        return apiResponse;
    }

    /**
     * 2.1 POST 用户注册接口
     *
     * @param user 要注册的用户的部分信息
     * @return 返回注册后的用户的全部信息，也就只是多个个自增id
     */
    @ApiOperation("2.1 POST 用户注册接口")
    @PostMapping("/api/v1/register")
    public ApiResponse<User> register(@ApiParam("要注册的用户信息") User user) {
        ApiResponse<User> apiResponse = new ApiResponse<>();
        try {
            userService.register(user);
            apiResponse.setCode(200).setSuccess(true).setMessage("请求成功").setData(user);
        } catch (Exception e) {
            apiResponse.setCode(500).setSuccess(false).setMessage("请求失败");
            e.printStackTrace();
        }
        return apiResponse;
    }

    /**
     * 用户登录（认证）接口
     *
     * @param user 登录（认证）的用户信息
     * @return 返回认证令牌
     */
    @PostMapping("/api/v1/login")
    public ApiResponse<Token> auth(User user) {
        ApiResponse<Token> apiResponse = new ApiResponse<>();
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

        User loginUser = userService.login(user);
        Token token = new Token();
        // 如果登录成功, 授予令牌
        if (loginUser != null) {
            String tokenValue = null;
            if (loginUser.getRoleType() == 0) {
                // tokenValue = TokenUtil.getSimpleToken();
                token.setTokenType(TokenType.SIMPLE);

            } else {
                token.setTokenType(TokenType.VIP);
                // 普通用户token有效期30分钟、VIP用户一小时
                token.setTtl(3600);
            }
            // 利用用户邮箱生成token
            tokenValue = JWTHS256.buildJWT(loginUser.getEmail());
            token.setTokenValue(tokenValue).setUserEmail(loginUser.getEmail());
            // java.time.Duration.ofSeconds(long seconds)方法获取表示秒数的Duration和以纳秒为单位的调整。
            operations.set("token:movie-api-v1:" + loginUser.getEmail(), tokenValue, Duration.ofSeconds(token.getTtl()));
            apiResponse.setData(token).setCode(200).setMessage("认证成功").setSuccess(true);
        } else {
            apiResponse.setSuccess(false).setCode(500).setMessage("认证失败");
        }

        return apiResponse;
    }
}
